package goomi.tool;

import javax.servlet.*;
import javax.servlet.http.*;

import db.mysql.mySqlUtils;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Map;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.File;

public class DownloadUtil extends HttpServlet{

	private static final String CONTENT_TYPE = "text/html; charset=UTF-8";
	private static final String FILE_CONTENT_TYPE = "application/octet-stream; charset=iso-8859-1";


	public void doGet( HttpServletRequest request, HttpServletResponse response )
	throws ServletException, IOException
	{
		doPost(request,response);
	}

	public void doPost( HttpServletRequest request, HttpServletResponse response )
	throws ServletException, IOException
	{
		try {
			String dest = "";
			String path = (String)request.getParameter("path");
			String id = (String)request.getParameter("id");
			
			System.out.println("pic 1path:" + path );
			System.out.println("pic id:" + id );
			
			if("img".equals(request.getParameter("type"))){
				dest = "img.jpg";
				if((path == null || "".equals(path)) && id != null){
					try{
						String sql = "select * from picture where id = '" +id+ "'";
						ArrayList pic = mySqlUtils.Query(sql);
						path = (String)((Map)pic.get(0)).get("path");
					}catch (Exception e) {
						e.printStackTrace();
						path = this.getServletContext().getRealPath("") + "\\img\\no.jpg";
					}
				}
			}
			System.out.println("pic path:" + path );
			this.download(request,response,path,dest);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * JSP/servlet FileDownload Helper.
	 * @param req form JSP/servlet pass Request Obj.
	 * @param resp form JSP/servlet pass Response Obj.
	 * @param src_fname Source file name. (full path)
	 * @param dst_fname Destination file name. (only need file name)
	 * @throws ServletException
	 * @throws IOException
	 */
	public void download(HttpServletRequest req, HttpServletResponse resp,
			String src_fname, String dst_fname) throws Exception {

		//src_fname = "D:\\apache-tomcat-7.0.19\\webapps\\Goomi\\img\\tra-ong.jpg";
		//dst_fname = URLEncoder.encode("測試.jpg");
		//dst_fname = "tra-ong.jpg";

		if (dst_fname == null)
			dst_fname="TemplateExcel";

		StringBuffer headTxt = new StringBuffer();
		//      String encDst_fname = new String(dst_fname.getBytes("Big5"), "ISO8859_1");
		//      req.setCharacterEncoding("big5");
		String encDst_fname = new String(dst_fname.getBytes(), "ISO8859_1");
		//      req.setCharacterEncoding("UTF-8");

		System.out.println("begin download " + dst_fname);

		if (dst_fname.endsWith(".jpg") || (dst_fname.endsWith(".gif"))) {
			//no need setting content type and header
			resp.setContentType("image/jpeg");
		} else if (dst_fname.endsWith(".txt")) {
			resp.setContentType(CONTENT_TYPE);
		} else {
			resp.setContentType(FILE_CONTENT_TYPE);
		}

		if (req.getHeader("User-Agent").indexOf("MSIE 5.5") != -1) {
			// MS IE5.5 ??��?��?�特?��??��??
			System.out.println(req.getHeader("User-Agent"));
			headTxt.append("filename=");
			headTxt.append(encDst_fname);

			resp.setHeader("Content-Disposition", headTxt.toString());
			headTxt.delete(0,headTxt.length());
		}
		else {
			// ??? IE5.5 ??? Header 設�?�方�?
			System.out.println(req.getHeader("User-Agent"));
			headTxt.append("attachment;filename=");
			headTxt.append(encDst_fname);

			resp.addHeader("Content-Disposition", headTxt.toString());
			headTxt.delete(0,headTxt.length());
		}

		System.out.println(src_fname);
		if(src_fname == null)
			return;

		try{
			File file = new File(src_fname);
			FileInputStream bis = new FileInputStream(file);
			OutputStream bos = resp.getOutputStream();

			byte[] buff = new byte[1024];
			int readCount = 0;
			int i = 0;
			readCount = bis.read(buff);
			while (readCount != -1){
				bos.write(buff, 0, readCount);
				readCount = bis.read(buff);
			}
			System.out.println("read finished!");
			if (bis!=null)
				bis.close();
			if (bos!=null)
				bos.close();

		}catch(ArrayIndexOutOfBoundsException arr_ex){
			return;
		}catch(Exception e){
			e.printStackTrace();
			throw e;
		}

	} //End of download()

	public static void download(HttpServletRequest req, HttpServletResponse resp,
			InputStream src_stream, String dst_fname) throws Exception {

		//String src_fname = "c:\\temp\\測試.txt";
		//String dst_fname = URLEncoder.encode("測試.txt");

		if (dst_fname == null)
			dst_fname="TemplateExcel";

		StringBuffer headTxt = new StringBuffer();
		//		      String encDst_fname = new String(dst_fname.getBytes("Big5"), "ISO8859_1");
		//		      req.setCharacterEncoding("big5");
		String encDst_fname = new String(dst_fname.getBytes(), "ISO8859_1");
		//		      req.setCharacterEncoding("UTF-8");

		if (dst_fname.endsWith(".jpg") || (dst_fname.endsWith(".gif"))) {
			//no need setting content type and header
		} else if (dst_fname.endsWith(".txt")) {
			resp.setContentType(CONTENT_TYPE);
		} else {
			resp.setContentType(FILE_CONTENT_TYPE);
		}

		if (req.getHeader("User-Agent").indexOf("MSIE 5.5") != -1) {
			// MS IE5.5
			headTxt.append("filename=");
			headTxt.append(encDst_fname);

			resp.setHeader("Content-Disposition", headTxt.toString());
			headTxt.delete(0,headTxt.length());
		}
		else {
			// IE5.5
			headTxt.append("attachment;filename=");
			headTxt.append(encDst_fname);

			resp.addHeader("Content-Disposition", headTxt.toString());
			headTxt.delete(0,headTxt.length());
		}

		try{
			OutputStream bos = resp.getOutputStream();

			byte[] buff = new byte[1024];
			int readCount = 0;
			int i = 0;
			readCount = src_stream.read(buff);
			while (readCount != -1){
				bos.write(buff, 0, readCount);
				readCount = src_stream.read(buff);
			}
			if (src_stream!=null)
				src_stream.close();
			if (bos!=null)
				bos.close();

		}catch(ArrayIndexOutOfBoundsException arr_ex){
			return;
		}catch(Exception e){
			e.printStackTrace();
			throw e;
		}

	} //End of download()  

} //End of DownLoadUtil()
